﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using RelightERP.DAL.EntityModel;

public partial class Admin_Login : System.Web.UI.Page
{
    #region PROPERTIES
    public string CompanyName
    {
        get { return Utility.GetCompanyName(); }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            using (RelightDBEntities context = new RelightDBEntities())
            {
                Users _Users = context.Users.FirstOrDefault(x => x.LoginID.ToUpper() == tbUserName.Text.ToUpper()
                                                      && x.Password.ToUpper() == tbPassword.Text.ToUpper());
                if (_Users != null)
                {
                    context.Users.FirstOrDefault(x => x.UserID == _Users.UserID).LastLoginDate = DateTime.Now;
                    context.SaveChanges();
                    OnLoginSuccess(_Users);
                }
                else
                {
                    divMsg.InnerHtml = "Invalid login."; //Resource.MsgResources.InvalidLogin;
                }
            }
        }
        catch (Exception ex)
        {
            Utility.ShowDhtmlAlert(this, ex.Message);
        }
        finally
        {
            GC.Collect();
        }        
    }

    private void OnLoginSuccess(Users _Users)
    {
        if (Session["CurrentUserID"] != null)
        {
            Session.Remove("CurrentUserID");
        }
        Session["CurrentUserID"] = _Users.UserID;

        // Prevent caching, so can't be viewed offline
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        FormsAuthentication.SetAuthCookie(_Users.LoginID, false);
        Response.Redirect(Utility.GetAdminHomePageUrl());
    } 

}